# coding=utf-8
import time
import os, sys
import random
BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
)
sys.path.insert(0,BASE_PATH)

from bin import get_Webdriver
from page_object.public import Public


class File_Manage:
    def __init__(self):
        self.driver = get_Webdriver.Get_Webdriver().driver

    def jumptoFilepage(self):
        curl = Public().getCurrentUrl()
        if '/documentmanager/main.html' not in curl:
            self.driver.click("link_text=>历史记录")
            self.driver.click("link_text=>历史文件")
        else:
            self.driver.F5()

    def clickNextPageButton(self):
        """点击下一页按钮"""
        # self.dr.find_element_by_xpath(self.r.nextPage_button_xpath).click()
        self.driver.click("css=>.page-next>a")

    # def inFolder(self,folderName):
    #     """进入子文件夹
    #     可选 plugins、sources、analysis  或其他文件夹"""
    #     pageCount = math.ceil(self.getFileCount() / 10)
    #     # if pageCount > 10: pageCount = 10
    #     findFlag = False
    #     for i in range(pageCount - 1):
    #         for j in range(1, 11):
    #             ele=self.dr.find_element_by_xpath(self.r.fileName_text_xpath.format(j))
    #             t_name = ele.text
    #             if t_name == folderName:
    #                 self.dr.find_element_by_xpath(self.r.folder_link_xpath.format(j)).click()
    #                 findFlag = True
    #                 break
    #         if findFlag: break
    #         try:
    #             self.clickNextPageButton()
    #         except:
    #             pass
    #     if not findFlag:
    #         print( "未找到__{}__文件夹".format(folderName))

    def getFileallCount(self):
        """获取当前条件下所有文件个数"""
        time.sleep(3)
        try:
            return int(self.driver.get_text('css=>.pagination-info').split(" ")[5])
        except IndexError:
            return "文件列表为空"

    def getFileCount(self):
        """获取当前页面文件个数"""
        time.sleep(3)
        try:
            lastcount = int(self.driver.get_text('css=>.pagination-info').split(" ")[3])
        except IndexError:
            return "文件列表为空"
        else:
            firstcount = int(self.driver.get_text('css=>.pagination-info').split(" ")[1])
            count = lastcount - firstcount + 1
            return count

    def getCurrentFileList(self):
        """获取当前页面的文件列表"""
        filecount = self.getFileCount()
        if filecount == "文件列表为空":
            print("文件列表为空")
            return ""
        else:
            fileList=[]
            for i in range(1, filecount+1):#第1到1000条信息
                fileList.append(self.driver.get_text("xpath=>.//*[@id='maingrid']/tbody/tr[{}]".format(i)))
            return fileList

    # def getAllFileList(self):
    #     """获取文件列表，最多返回前100条"""
    #     pageCount = math.ceil(self.getFileCount()/10)
    #     if pageCount > 10:
    #         pageCount=10
    #     fileList=[]
    #     for i in range(pageCount):
    #         for j in range(1,11):
    #             try:fileList.append(self.dr.find_element_by_xpath(self.r.fileDetails_text_xpath.format(j)).text)
    #             except:pass
    #         try:self.clickNextPageButton()
    #         except:pass
    #     return fileList

    def selectFileByindexlist(self, indexlist):
        """点选文件前的复选框，最多检索前10页"""
        for index in indexlist:
            self.driver.click("xpath=>//table[@id='maingrid']/tbody/tr[{}]/td[1]/input".format(index))

    def deleteFileByindex(self, index):
        """点击文件后的删除按钮"""
        self.driver.click("xpath=>.//*[@id='maingrid']/tbody/tr[{}]//*[@class='icon-trash']".format(index))

    def downloadFileByindex(self, index):
        """下载文件 最多检索前10页  暂时不能自动下载文件 """
        self.driver.click("xpath=>//table[@id='maingrid']/tbody/tr[{}]/td[6]/div/a[1]/i".format(index))

    def clickDeleteButton(self):
        """点击表格上方的删除按钮 """
        self.driver.click("css=>span.icon-trash")

    def selectFileFromFileList(self, fileList, much=1):
        """从文件理列表中随机选择出文件的名称并返回"""
        fileListCount = len(fileList)
        fileNameList = []
        indexlist = []
        for i in range(much):
            while 1:
                index = random.randint(0, fileListCount-1)
                xpathindex = index + 1
                fileName = fileList[index].split(" ")[1]
                if fileName not in ["analysis", "comment", "plugins", "sources"] and fileName not in fileNameList:
                    fileNameList.append(fileName)
                    indexlist.append(xpathindex)
                    break
        return fileNameList, indexlist

    def selectFolderFromFileList(self, fileList, much=1):
        """从文件理列表中随机选择出文件夹子的序号的名称并返回"""
        fileListCount = len(fileList)
        fileNameList = []
        indexlist = []
        for i in range(much):
            while 1:
                index = random.randint(0, fileListCount-1)
                xpathindex = index + 1
                fileName = fileList[index].split(" ")[1]
                if fileName in ["analysis", "comment", "plugins", "sources"] and fileName not in fileNameList:
                    fileNameList.append(fileName)
                    indexlist.append(xpathindex)
                    break
        return fileNameList, indexlist

    def isFileInCurrentPage(self, fileNameList):
        """判断文件是否在当前页面 并返回布尔值"""
        currentFileDetials = self.getCurrentFileList()
        currentFileList = []
        for currentFileDetial in currentFileDetials:
            currentFileList.append(currentFileDetial.split(" ")[1])
        print(fileNameList)
        print(currentFileList)
        flag = True
        for fileName in fileNameList:
            if fileName in currentFileList:
                flag = False
        return flag

    def chooseNumberOfPage(self, number):
        """选择每页条数"""
        if number == "10":
            index = "1"
        elif number == "25":
            index = "2"
        elif number == "50":
            index = "3"
        elif number == "100":
            index = "4"
        else:
            return "每页条数不对"
        self.driver.click("css=>button[class='btn btn-default dropdown-toggle']")
        time.sleep(0.5)
        self.driver.click("xpath=>.//*[@role='menu']/li[{}]".format(index))

    def getNumberOfPage(self):
        """获取当前所载页面页码"""
        pageNo = self.driver.get_text("css=>.page-number.active>a")
        return pageNo


if __name__ == '__main__':
    pass